import logging

from google.appengine.api import xmpp
from google.appengine.ext import webapp, db
from google.appengine.api import mail
from logger.models import LogEntry, LogSubscriber
from logger.settings import SETTINGS

class Worker(webapp.RequestHandler):

    def post(self):

        timestamp = self.request.get('timestamp', '')
        domain = self.request.get('domain', '')
        context = self.request.get('context', '')
        msg_key = self.request.get('msg_key', '')
        msg_value = self.request.get('msg_value', '')
        eventtype = self.request.get('eventtype', '')

        subscribers = LogSubscriber.all().fetch(1000)

        subscriber = {
            'xmpp' : {},
            'email' : {}}
        for s in subscribers:
            if s.domain and domain!=s.domain:
                break
            if s.context and s.context!=context:
                break
            if s.msg_key and s.msg_key!=msg_key:
                break
            if s.eventtype and s.eventtype!=eventtype:
                break
            subscriber[s.receiver_type][s.receiver_address] = s

        msg='event %s on context %s on domain %s kv: %s %s; %s' % \
             (eventtype, context, domain, msg_key, msg_value, timestamp)

        jid_sender = SETTINGS.get('jid_sender')
        email_sender = SETTINGS.get('email_sender')


        for rcv in subscriber['xmpp'].values():
            jid=rcv.receiver_address
            logging.debug('%s send jabber to %s msg: %s' % (jid,jid_sender,msg))
            if xmpp.get_presence(jid, jid_sender):
                status_code = xmpp.send_message(jid, msg,
                                                from_jid=jid_sender)

        for rcv in subscriber['email'].values():
            logging.debug('%s send mail msg: %s' % (rcv.receiver_address,msg))
            mail.send_mail(email_sender,
                           rcv.receiver_address,
                           'gae logger notification',
                           msg)

